package wlt.plan.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import wlt.plan.model.TodoItem;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

public class TodoManager {
    private final Map<LocalDate, ObservableList<TodoItem>> todoItemsByDate;
    private static final String DATA_FILE_PATH = "todo_data.json";
    private final ObjectMapper objectMapper;
    private final LocalDate currentDate;
    
    public TodoManager() {
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule()); // 注册Java 8日期模块
        this.todoItemsByDate = new HashMap<>();
        this.currentDate = LocalDate.now();
        loadTasks();
    }
    
    public ObservableList<TodoItem> getTodoItemsForDate(LocalDate date) {
        ObservableList<TodoItem> items = todoItemsByDate.computeIfAbsent(date, k -> FXCollections.observableArrayList());
        
        // 按优先级高中低排序，且未完成的任务排在前面
        FXCollections.sort(items, (item1, item2) -> {
            // 按完成状态排序
            if (item1.isCompleted() != item2.isCompleted()) {
                // 未完成的排前面
                return Boolean.compare(item1.isCompleted(), item2.isCompleted());
            }
            
            // 按优先级排序
            return item2.getPriority().compareTo(item1.getPriority());
        });
        
        return items;
    }
    
    // 添加支持优先级的addTodoItem方法
    public void addTodoItem(String text, LocalDate date, TodoItem.Priority priority) {
        if (text != null && !text.trim().isEmpty()) {
            getTodoItemsForDate(date).add(new TodoItem(text.trim(), date, priority));
            saveTasks();
        }
    }
    
    // 标记任务为已完成
    public void markItemAsCompleted(TodoItem item) {
        if (item != null && !item.isCompleted()) {
            item.setCompleted(true);
            saveTasks();
        }
    }
    
    // 获取当前日期
    public LocalDate getCurrentDate ( ) {
        return currentDate;
    }
    
    // 删除任务
    public void deleteItem(TodoItem item) {
        if (item != null) {
            ObservableList<TodoItem> items = getTodoItemsForDate(item.getDate());
            if (items != null) {
                items.remove(item);
                // 如果某天没有待办事项了，删除该日期的映射
                if (items.isEmpty()) {
                    todoItemsByDate.remove(item.getDate());
                }
                saveTasks();
            }
        }
    }
    
    // 保存待办事项到文件
    public void saveTasks() {
        try {
            // 转换为适合JSON存储的格式
            List<TodoItem> allItems = todoItemsByDate.values().stream()
                                                     .flatMap(Collection ::stream)
                                                     .collect(Collectors.toList());
            objectMapper.writeValue(new File(DATA_FILE_PATH), allItems);
        } catch (IOException e) {
            System.err.println("保存待办事项失败: " + e.getMessage());
        }
    }
    
    // 从文件加载待办事项
    private void loadTasks() {
        try {
            File dataFile = new File(DATA_FILE_PATH);
            if (dataFile.exists()) {
                TodoItem[] itemsArray = objectMapper.readValue(dataFile, TodoItem[].class);
                
                // 按日期重新组织待办事项
                for (TodoItem item : itemsArray) {
                    getTodoItemsForDate(item.getDate()).add(item);
                }
            }
        } catch (IOException e) {
            System.err.println("加载待办事项失败: " + e.getMessage());
        }
    }
}
